<template>
  <div class="editor-container">
    <div ref="quillEditor" class="editor"></div>
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      @change="handleImageUpload"
      style="display: none;"
    />
    <div class="output">
      <h3>输出的 HTML 内容：</h3>
      <pre>{{ editorContent }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
import ImageResize from 'quill-image-resize-module-plus';
import axios from 'axios';
import { useUserStore } from '../stores/user';

const userStore = useUserStore();
const quillEditor = ref(null);
const fileInput = ref(null);
const editorContent = ref('');
let quill = null;

// 注册模块
Quill.register('modules/imageResize', ImageResize);

onMounted(() => {
  const toolbarOptions = [
    [{ font: [] }],
    [{ size: ['small', false, 'large', 'huge'] }],
    ['bold', 'italic', 'underline', 'strike'],
    [{ color: [] }, { background: [] }],
    [{ header: 1 }, { header: 2 }, 'blockquote', 'code-block'],
    [{ list: 'ordered' }, { list: 'bullet' }],
    [{ align: [] }],  // 确保有对齐选项
    ['link', 'image', 'video'],
    ['clean'],
  ];

  quill = new Quill(quillEditor.value, {
    theme: 'snow',
    modules: {
      toolbar: {
        container: toolbarOptions,
        handlers: {
          image: selectLocalImage,
        },
      },
      imageResize: {},
    },
    placeholder: '请输入内容...',
  });

  quill.on('text-change', () => {
    editorContent.value = quill.root.innerHTML;
  });
});

// 点击工具栏图片按钮
function selectLocalImage() {
  fileInput.value.click();
}

// 处理上传图片
async function handleImageUpload(event) {
  const file = event.target.files[0];
  if (!file) return;

  const formData = new FormData();
  formData.append('image', file);

  try {
    const res = await axios.post('/api/upload', formData, {
      headers: { token: userStore.token },
    });

    if (res.data.code === 1) {
      const imageUrl = res.data.data;
      console.log('图片上传成功，图片URL：', imageUrl);
      insertToEditor(imageUrl);
    } else {
      console.error('上传失败', res.data.msg || '未知错误');
    }
  } catch (error) {
    console.error('上传异常', error);
  }
}

// 插入图片到编辑器，套 <p> 标签
function insertToEditor(url) {
  const range = quill.getSelection(true);
  if (range) {
    quill.insertText(range.index, '\n', 'user');
    quill.insertEmbed(range.index + 1, 'image', url, 'user');
    quill.insertText(range.index + 2, '\n', 'user');
  } else {
    quill.insertEmbed(quill.getLength(), 'image', url, 'user');
  }
}
</script>

<style scoped>
.editor-container {
  width: 80%;
  margin: 0 auto;
}

.editor {
  height: 500px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background: #fff;
}

.output {
  margin-top: 20px;
  background: #f5f5f5;
  padding: 10px;
  border-radius: 8px;
  word-break: break-word;
}

/* 确保图片居中、对齐样式应用 */
.ql-align-center img {
  display: block;
  margin: 0 auto;
}

.ql-align-right img {
  display: block;
  margin-left: auto;
}

.ql-align-left img {
  display: block;
  margin-right: auto;
}

/* 必须有对齐按钮才能使功能生效 */
.ql-toolbar button {
  margin-right: 5px;
}

.ql-toolbar .ql-align {
  margin-left: 5px;
}
</style>
